package com.pokermind.dse.tcp.server;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

/**
 * TCP Server Starter
 * TCP服务器启动器，在Spring Boot应用启动完成后自动启动TCP服务器
 * 
 * 启动流程：
 * 1. Spring Boot应用启动完成
 * 2. 所有Bean初始化完成
 * 3. 执行run方法启动TCP服务器
 * 4. TCP服务器开始监听端口并处理连接
 * 
 * @author PokerMind Team
 */
@Component
public class TcpServerStarter implements CommandLineRunner {

    private static final Logger logger = LoggerFactory.getLogger(TcpServerStarter.class);

    @Autowired
    private NettyTcpServer nettyTcpServer;

    @Override
    public void run(String... args) throws Exception {
        logger.info("Starting TCP Server...");
        
        try {
            // 在新线程中启动TCP服务器，避免阻塞主线程
            Thread tcpServerThread = new Thread(() -> {
                try {
                    nettyTcpServer.start();
                } catch (Exception e) {
                    logger.error("Failed to start TCP Server: {}", e.getMessage(), e);
                    // 启动失败时退出应用
                    System.exit(1);
                }
            }, "tcp-server-starter");
            
            tcpServerThread.setDaemon(false); // 非守护线程，保持应用运行
            tcpServerThread.start();
            
            // 等待一段时间确保服务器启动
            Thread.sleep(1000);
            
            if (nettyTcpServer.isRunning()) {
                logger.info("TCP Server started successfully");
            } else {
                logger.error("TCP Server failed to start");
                System.exit(1);
            }
            
        } catch (Exception e) {
            logger.error("Error during TCP Server startup: {}", e.getMessage(), e);
            System.exit(1);
        }
    }
}
